package com.neusoft.controller;

import com.neusoft.po.CommonResult;
import com.neusoft.po.Coupon;
import com.neusoft.service.CouponService;
import com.neusoft.util.CommonUtil;
import com.neusoft.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/CouponController")
public class CouponController {

    @Autowired
    private CouponService couponService;

    // 通过用户Id获取优惠券信息
    @GetMapping("/getCouponById/{tokenString}")
    public CommonResult getCouponById(@PathVariable("tokenString") String tokenString) {
        try {
            TokenUtil.verify(tokenString);
        }catch(Exception e){
            return new CommonResult(401, "Unauthorized", 0);
        }
        if(TokenUtil.verify(tokenString)) {
            String userId = TokenUtil.tokenUser(tokenString);
            Coupon coupon =  couponService.getCouponById(userId);
            return new CommonResult(200, "success", coupon);
        }else {
            return new CommonResult(401, "Unauthorized", 0);
        }
    }

    // 通过用户Id增加他的优惠券
    @PutMapping("/addCoupon/{tokenString}/{coupon_10_2}/{coupon_20_3}/{coupon_30_5}/{coupon_20_6}/{coupon_30_10}/{coupon_50_15}")
    public CommonResult addCoupon(@PathVariable("tokenString") String tokenString,
                            @PathVariable("coupon_10_2") Integer coupon_10_2,
                            @PathVariable("coupon_20_3") Integer coupon_20_3,
                            @PathVariable("coupon_30_5") Integer coupon_30_5,
                            @PathVariable("coupon_20_6") Integer coupon_20_6,
                            @PathVariable("coupon_30_10") Integer coupon_30_10,
                            @PathVariable("coupon_50_15") Integer coupon_50_15
                            ) {
        Coupon coupon = new Coupon();
        coupon.setCoupon_10_2(coupon_10_2);
        coupon.setCoupon_20_3(coupon_20_3);
        coupon.setCoupon_20_6(coupon_20_6);
        coupon.setCoupon_30_5(coupon_30_5);
        coupon.setCoupon_30_10(coupon_30_10);
        coupon.setCoupon_50_15(coupon_50_15);
        coupon.setStartDate(CommonUtil.getCurrentDate());
        try {
            TokenUtil.verify(tokenString);
        }catch(Exception e){
            return new CommonResult(401, "Unauthorized", 0);
        }
        if(TokenUtil.verify(tokenString)) {
            String userId = TokenUtil.tokenUser(tokenString);
            coupon.setUserId(userId);
            Coupon coupon_1 =  couponService.addCoupon(coupon);
            return new CommonResult(200, "success", coupon_1);
        }else {
            return new CommonResult(401, "Unauthorized", 0);
        }
    }
}
